import React, { useEffect, useRef, useState } from 'react';
import { Table, Row, Col } from 'antd';
import { getPageMeta } from '@/services/request/meta';
import _ from 'lodash';
import { ColumnsType } from 'antd/lib/table';
import { toJS } from '@formily/reactive'
import { TableRenderProps } from './types';
import DefaultTable from './default-table';
import EditableTable, { EditableDefaultProps } from './editable-table';
import { initialSchema } from './utils';

export interface TableProps extends EditableDefaultProps, TableRenderProps {
  nested?: boolean; // 是否可嵌套子表格
  nestedTableColumns?: ColumnsType<any>; // 嵌套表格的columns
  nestedTableDataKey?: string; // 嵌套表格数据对应主表格数据的字段
  type: 'DETAILS' | 'EDIT' | 'NESDETAILS';
  pageCode?: string; // 获取页面配置
  api?: {
    url?: string,
    type?: 'POST' | 'GET',
    param?: any
  } // 拉去数据
}

const EditTable = (props: TableProps) => {
  const [colum, setColum] = useState<any>([]);
  const [colsMap, setColsMap] = useState<any>({});
  const {
    type = 'DETAILS',
    pageCode,
    api,
    nestedTableColumns = [],
    nestedTableDataKey = '',
    extraAction,
    eventMap = {},
    ...otherProps
  } = props;
  // 处理 editableColsMap
  // onEditableRowSave
  /**
   * 子表格渲染
   * @param record 
   * @returns 
   */

  const expandedRowRender = (record: any) => {
    return <Table columns={nestedTableColumns} dataSource={record[nestedTableDataKey]} pagination={false} />;
  }
  useEffect(() => {
    if (pageCode) {
      getPageMeta(pageCode).then((res: any) => {
        const da = initialSchema(res.result, 'NORMAL', eventMap);
        setColum(da.columns);
        setColsMap(da.colsMap);
      }).catch((err) => {
        console.log(`${pageCode}获取数据失败`)
      })
    }
  }, [pageCode])
  /*
  ** 获取渲染的页面
  */
  const renderTable = () => {
    const tableEnum = {
      'DETAILS': <DefaultTable {...otherProps} columns={colum} rowsRender={toJS(eventMap?.rowsRender) || ''} />,
      'NESDETAILS': <DefaultTable
        {...otherProps}
        className="components-table-demo-nested"
        expandedRowRender={expandedRowRender}
      />,
      'EDIT': <EditableTable {...otherProps} defaultColumns={colum} editableColsMap={colsMap} rowsRender={toJS(eventMap?.rowsRender) || ''} />
    }
    return tableEnum[type]
  }
  return (
    <Row>
      <Col span={24}>
        {extraAction && extraAction.length ? <Row className="extra__Action">{extraAction}</Row> : null}
        <Row>
          {
            renderTable()
          }
        </Row>
      </Col>
    </Row>
  )
}

export default EditTable;